package com.xunshibao.action.message;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xunshibao.core.dao.page.Pagination;
import com.xunshibao.entity.message.Message;
import com.xunshibao.entity.message.MsgReply;
import com.xunshibao.entity.user.UserLogin;
import com.xunshibao.message.MessageServiceImpl;
import com.xunshibao.service.message.MessageDRO;
import com.xunshibao.util.SessionKey;
import com.xunshibao.web.security.Security;

@Controller
@RequestMapping(value = "/message")
@Security
public class MessageController {
	private MessageServiceImpl msgService;

	@Autowired
	public void setMsgService(MessageServiceImpl msgService) {
		this.msgService = msgService;
	}

	@RequestMapping(value = "/inbox")
	public String listInbox(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		int pageNo = 0;
		String pageNoStr = request.getParameter("pageNo");
		if(pageNoStr != null) {
			pageNo = Integer.parseInt(pageNoStr);
		}
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			model.addAttribute("message", "你还没有登录，请先登录后再操作");
			model.addAttribute("redirecturl", "/message/inbox");
			return "system/message";
		}
		
		MessageDRO dro = msgService.listInbox(currentUser.getUid(), pageNo, 10);//TODO

//		MessageDRO dro = msgService.listUserInbox(currentUser.getUid(), 0, 10); // TODO
																				// userId
		// 和分页参数
		model.addAttribute("dro", dro);
//		model.addAttribute("relations", dro.getPage().getList());
//		model.addAttribute("messages", dro.getMessages());
		return "message/inbox";
	}

	@RequestMapping(value = "/system")
	public String listSystem(Model model, HttpSession session) {
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			model.addAttribute("message", "你还没有登录，请先登录后再操作");
			model.addAttribute("redirecturl", "/message/inbox");
			return "system/message";
		}
		
		MessageDRO dro = msgService.listSystem(currentUser.getUid(), 0, 10);//TODO

		// 和分页参数
		model.addAttribute("dro", dro);
		model.addAttribute("system", true);
		return "message/system";
	}
	
	@RequestMapping(value = "/readsys")
	public String readsys(@RequestParam(value = "msgId") Long msgId, Model model, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			model.addAttribute("message", "你还没有登录，请先登录后再操作");
			model.addAttribute("redirecturl", "/message/inbox");
			return "system/message";
		}
		
		List<Message> messages = msgService.readSysMessage(currentUser.getUid(), msgId);

		// 和分页参数
		model.addAttribute("messages", messages);
		model.addAttribute("system", true);
		return "message/sysread";
	}
	
	@RequestMapping(value = "/show")
	public String view(@RequestParam(value = "msgId") Long msgId, Model model, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			model.addAttribute("message", "你还没有登录，请先登录后再操作");
			model.addAttribute("redirecturl", "/message/inbox");
			return "system/message";
		}

		int newPmCnt = Integer.parseInt(getCookieValue("msgcount", request));
//		List<MsgReply> replies = msgService.readMsg(msgId, currentUser.getUid(), newPmCnt);
		List<MsgReply> replies = msgService.readMsg(currentUser.getUid(), msgId);
		if (newPmCnt > 0)
			--newPmCnt;
		else
			newPmCnt = 0;
		setCookieValue("msgcount", newPmCnt+"", response);
		model.addAttribute("replies", replies);
		model.addAttribute("username", "haiker");// TODO 当前用户的用户名
		return "message/read";
	}

	private String getCookieValue(String cookieKey, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String value = null;
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (c.getName().equals(cookieKey)) {
					value = c.getValue();
					break;
				}
			}
		}
		return value;
	}
	
	private void setCookieValue(String cookieKey, String value, HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieKey, value);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	@RequestMapping(value = "/reply")
	public @ResponseBody
	Map<String, Object> reply(@RequestParam(value = "msgId") Long msgId, @RequestParam(value = "content") String content, HttpSession session) {
		Map<String, Object> json = new HashMap<String, Object>();
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			json.put("result", false);
			json.put("message", "您还没有登录，请先登录");
			return json;
		}
		Long curUID = currentUser.getUid();// 当前用户编号
		String username = currentUser.getUsername(); // 当前用户名
//		boolean retV = msgService.replyMsg(msgId, curUID, username, content);
		int retV = msgService.reply(curUID, username, msgId, content);
		if (retV == 0) {
			json.put("result", true);
		} else {
			json.put("result", false);
		}
		return json;
	}

	@RequestMapping(value = "/send")
	public @ResponseBody
	Map<String, Object> send(@RequestParam(value = "title") String title, @RequestParam(value = "nick") String receiver,
			@RequestParam(value = "cont") String content, HttpSession session) {
		Map<String, Object> json = new HashMap<String, Object>();
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			json.put("result", false);
			json.put("message", "您还没有登录，请先登录");
			return json;
		}
		Long curUID = currentUser.getUid();// 当前用户编号
		String username = currentUser.getUsername(); // 当前用户名
		Long rid = msgService.getUserIdByName(receiver);
		if (rid != null) {
//			boolean retV = msgService.sendUserMessage(curUID, Arrays.asList(rid), username, title, content);
			int retV = msgService.sendMessage(curUID, username, Arrays.asList(rid), title, content);
			if (retV == 0) {
				json.put("result", true);
				json.put("message", "发送成功");
			} else {
				json.put("result", false);
				json.put("message", "发送失败");
			}
		} else {
			json.put("result", false);
			json.put("message", "收件人不存在");
		}

		return json;
	}

	@RequestMapping(value = "/delete")
	public @ResponseBody
	Map<String, Object> delete(@RequestParam(value = "mid") Long mid, HttpSession session) {
		Map<String, Object> json = new HashMap<String, Object>();
		UserLogin currentUser = (UserLogin) session.getAttribute(SessionKey.USER_KEY);
		if (currentUser == null) {
			json.put("result", false);
			json.put("message", "你还没有登录，请先登录");
		}
		Long curUID = currentUser.getUid();// 当前用户编号

		int retV = msgService.delete(curUID, mid);
		if (retV == 0) {
			json.put("result", true);
			json.put("message", "删除成功");
		} else {
			json.put("result", false);
			json.put("message", "删除失败");
		}
		return json;
	}
	
	@RequestMapping(value = "/page")
    public String delete(HttpServletRequest req, Model model) {
	    //TODO 测试用的方法
	    int pageNo = 0;
	    String p = req.getParameter("pageNo");
	    if(p != null) {
	        pageNo = Integer.parseInt(p);
	    }
	    Pagination page = new Pagination(pageNo, 5, 107);
	    model.addAttribute("page", page);
        return "message/page";
    }
}
